package org.test.device.architecture.utils;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

import java.util.Map;

/**
 * 〈〉<br>
 *
 * @author Mr.Wang
 * @create 2024/9/9
 */
@Slf4j
@Component
public class SpringContextHolder  implements ApplicationContextAware, DisposableBean {

    private static ApplicationContext applicationContext;

    /**
     * 实现DisposableBean接口, 在Context关闭时清理静态变量
     */
    @Override
    public void destroy() throws Exception {
        SpringContextHolder.clearHolder();
    }

    /**
     * 清除SpringContextHolder中的ApplicationContext为Null
     */
    private static void clearHolder(){
        applicationContext=null;
    }

    /**
     * 实现ApplicationContentAware接口，将ApplicationContent注入到静态变量中
     */
    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        SpringContextHolder.applicationContext = applicationContext;
    }

    /**
     * 获取SpringContext
     * @return
     */
    public static ApplicationContext getApplicationContext() {
        return applicationContext;
    }

    /**
     * 从静态变量ApplicationContent中获取Bean，并自动转型为请求的类型
     */
    public static <T> T getBean(Class<T> requiredType){
        return applicationContext.getBean(requiredType);
    }

    public static <T> Map<String, T> getBeanOfType(Class<T> requiredType){
        return applicationContext.getBeansOfType(requiredType);
    }


    public static <T> T getBean(String name, Class<T> requiredType) {
        return applicationContext.getBean(name, requiredType);
    }
}